﻿using System.IO;
using Lucene.Net.Store;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace Lucene.Linq.Azure
{
    public class AzureDriveDirectory : FSDirectory
    {
        private readonly CloudDrive drive;

        public AzureDriveDirectory(CloudStorageAccount account, string drivePath)
        {
            LocalResource azureDriveCache = RoleEnvironment.GetLocalResource("DriveLocalCache");
            CloudDrive.InitializeCache(azureDriveCache.RootPath + "cache", azureDriveCache.MaximumSizeInMegabytes);
            drive = account.CreateCloudDrive(drivePath);
            drive.CreateIfNotExist(16);
            directory = new DirectoryInfo(drive.Mount(azureDriveCache.MaximumSizeInMegabytes, DriveMountOptions.None));
            lockFactory = new NativeFSLockFactory();
        }

        public override void Close()
        {
            drive.Unmount();
            base.Close();
        }
    }
}
